<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ id: record.id })">
          {{ record.delegateState ? t('【委托】') : '' }}
          {{ record.procIns?.name || t('未设置流程名') }}
          {{ record.description ? '-' + record.description : '' }}
        </a>
      </template>
    </BasicTable>
    <component
      :is="inputFormComponent"
      v-model:visible="inputFormVisible"
      @register="registerDrawer"
      @success="handleSuccess"
    />
    <BpmRuntimeTrace @register="registerTraceModal" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBpmBpmMyTaskTodoList',
  });
</script>
<script lang="ts" setup>
  import { ComponentOptions, defineComponent, ref, shallowRef } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { bpmMyTaskList, bpmMyTaskForm } from '/@/api/bpm/myTask';
  import { bpmCategoryTreeData } from '/@/api/bpm/category';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { FormProps } from '/@/components/Form';
  import { dynamicImport } from '/@/router/helper/routeHelper';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { BpmRuntimeTrace } from '/@/components/Bpm';
  import qs from 'qs';

  const { t } = useI18n('sys.config');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('已办任务'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('流程名称'),
        field: 'procIns.name',
        component: 'Input',
      },
      {
        label: t('环节名称'),
        field: 'name',
        component: 'Input',
      },
      {
        label: t('创建时间'),
        field: 'dateRange',
        component: 'RangePicker',
        componentProps: {},
      },
      {
        label: t('流程分类'),
        field: 'procIns.procDef.category',
        component: 'TreeSelect',
        componentProps: {
          api: bpmCategoryTreeData,
          params: { isShowCode: '1' },
          allowClear: true,
        },
      },
      // {
      //   label: t('优先级'),
      //   field: 'priority',
      //   component: 'RadioGroup',
      //   componentProps: {
      //     dictType: 'bpm_task_priority',
      //     allowClear: true,
      //   },
      // },
    ],
    fieldMapToTime: [['dateRange', ['beginDate', 'endDate']]],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('流程名称'),
      dataIndex: 'procIns.name',
      key: 'processInstanceName',
      sorter: true,
      width: 230,
      align: 'left',
      slots: { customRender: 'firstColumn' },
    },
    {
      title: t('当前环节'),
      dataIndex: 'name',
      key: 'name',
      sorter: true,
      width: 100,
      align: 'center',
      customRender: ({ record }) => {
        return record.name || t('未设置环节名');
      },
    },
    {
      title: t('分配人员'),
      dataIndex: 'assigneeInfo',
      sorter: false,
      width: 100,
      align: 'center',
    },
    {
      title: t('优先级'),
      dataIndex: 'priority',
      key: 'priority',
      sorter: true,
      width: 50,
      align: 'center',
      dictType: 'bpm_task_priority',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => [
      {
        icon: 'fluent:flowchart-20-regular',
        title: t('流程追踪'),
        onClick: handleTrace.bind(this, record),
      },
      {
        icon: 'mdi:checkbox-marked-outline',
        title: t('任务办理'),
        onClick: handleForm.bind(this, { id: record.id }),
        ifShow: () => !(record.endTime && record.endTime != ''),
      },
    ],
  };

  const [registerTable, { reload }] = useTable({
    api: bpmMyTaskList,
    beforeFetch: (params) => {
      params.status = '2';
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
  });

  const [registerDrawer, { setDrawerData }] = useDrawer();
  const inputFormComponent = shallowRef<Nullable<any>>(null);
  const inputFormVisible = ref<Boolean>(false);

  async function handleForm(record: Recordable) {
    const data = await bpmMyTaskForm(record);
    if (data.result == 'true') {
      const url = data.pcViewUrl && data.pcViewUrl != '' ? data.pcViewUrl : data.pcUrl;
      const idx = url.indexOf('?');
      // component
      let component: ReturnType<typeof defineComponent>;
      const compStr = idx == -1 ? url : url.substring(0, idx);
      if (compStr && compStr != '') {
        const imp = dynamicImport(compStr);
        if (imp) component = createAsyncComponent(imp);
      }
      // params
      let params = {};
      const paramStr = idx == -1 ? '' : url.substring(idx + 1);
      if (paramStr && paramStr != '') {
        params = qs.parse(paramStr);
      }
      // open
      if (component) {
        inputFormComponent.value = component;
        inputFormVisible.value = true;
        setDrawerData(params);
      }
    } else {
      showMessage(data.message);
    }
  }

  function handleSuccess() {
    reload();
  }

  const [registerTraceModal, { openModal: traceModel }] = useModal();

  function handleTrace(record: Recordable) {
    traceModel(true, record.procIns);
  }
</script>
